import { Injectable } from '@nestjs/common';
import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
import { join } from 'path';
import * as StreamZip from 'node-stream-zip';


@Injectable()
export class Files2xlsxService {
    private getFiles(path: string) {
        if (!existsSync(path)) return [];
        const stat = statSync(path);
        if (stat.isFile()) {
            if (path.slice(path.lastIndexOf(".") + 1) !== "txt") return [];
            return [path];
        }
        const names = readdirSync(path);
        const ans = [];
        for (const name of names) {
            const arr = this.getFiles(join(path, name));
            for (const item of arr) ans.push(item);
        }
        return ans;
    }
    public parse(path: string) {
        const files = this.getFiles(path);
        const data = [];
        console.log(files)
        for (const file of files) {
            const filePath = join(path, file);
            const text = readFileSync(filePath, "utf8");
            data.push([file, text])
        }
        return data;
    }
    public save(file: string) {
        return new Promise(resolve => {
            const zip = new StreamZip({
                file,
                storeEntries: true
            });
            zip.on('ready', () => {
                console.log('Entries read: ' + zip.entriesCount);
                const files = [];
                for (const entry of Object.values(zip.entries())) {
                    const desc = entry.isDirectory ? 'directory' : `${entry.size} bytes`;
                    console.log(`Entry ${entry.name}: ${desc}`);
                }
                zip.close()
            });
            resolve
        })
    }
}
